package sk.stancel.peter.sudoku.activities;

import sk.stancel.peter.sudoku.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;

public class Dialog extends android.app.Dialog implements android.view.View.OnClickListener{

	private Context context;
	private EditText editText;
	
	public Dialog(Context context) {
		super(context);
		this.context = context;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog);
        setCancelable(true);
                
        LayoutParams params = getWindow().getAttributes();
        params.width = LayoutParams.FILL_PARENT;
        getWindow().setAttributes(params);
        
        editText = (EditText) findViewById(R.id.edittext);
        
		editText.requestFocus();
		getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		
		setTitle(R.string.dialog_title);
		editText.addTextChangedListener(new TextWatcher(){
	        public void afterTextChanged(Editable s) {
	        	setTitle(context.getString(R.string.set) + " " + (81 - s.toString().length()) + " " + context.getString(R.string.numbers));
	        }
	        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
	        public void onTextChanged(CharSequence s, int start, int before, int count){}
	    });
		
        Button create = (Button) findViewById(R.id.button_create);
        create.setOnClickListener(this);
	}

	public void onClick(View v) {
		if(v.getId() == R.id.button_create){
			String text = editText.getText().toString().trim();
	        if(text.matches("\\d{81}")){
	        	Bundle bundle = new Bundle();
	        	
	        	int[] ints = new int[text.length()];
	        	for (int i = 0; i < text.length(); i++) {
	        		ints[i] = Character.digit(text.charAt(i), 10);
	        	}
	        	bundle.putIntArray("int_array", ints);
	        	
	        	Intent intent = new Intent(context, SudokuActivity.class);
				intent.putExtras(bundle);
				context.startActivity(intent);
	        }else {
	        	AlertDialog.Builder builder = new AlertDialog.Builder(context);
	        	builder.setTitle(R.string.numbers_81).setCancelable(true).setIcon(android.R.drawable.ic_dialog_alert);
	        	AlertDialog alert = builder.create();
				alert.show();
	        }
		}
	}

	
}
